package com.xy.netty.dome.handler;

import com.xy.netty.dome.constant.CommonConstant;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author 1
 */
@Slf4j
public class EchoClientDelimiterHandler extends SimpleChannelInboundHandler<ByteBuf> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        log.info("Client received：{}",msg.toString(CharsetUtil.UTF_8));
    }


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Active");
        String msg = null;
        for (int i = 1; i <= 10; i++) {
             msg = String.format("%s客户端发送信息测试：%s",System.lineSeparator(),i);
             if(i%2==0){
                 msg += CommonConstant.NEWS_END_DELIMITER;
             }
            ctx.writeAndFlush(Unpooled.copiedBuffer(msg,CharsetUtil.UTF_8));
        }
        log.info("发送测试信息成功");
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("EchoClientDelimiterHandler channelReadComplete");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("exceptionCaught",cause);
        ctx.close();
    }
}
